import { getRolesListFromApi, useUserStore, getUserByIdFromApi, updateUserRolesFromApi } from '@/store/user/useUserStore'
import { Button, Checkbox } from 'antd';
import React, { useEffect, useState } from 'react';
import { useParams,useNavigate } from 'react-router-dom';

const Assign = () => {
    const getRolesLists = useUserStore.getState().getRolesLists;
    const rolesList = useUserStore.getState().rolesList
    const [checkBox, setCheckBox] = useState([])
    const route = useParams()
    const navigate= useNavigate()
    useEffect(() => {
        getRolesListFromApi()
        getUserByIdFromApi(route.id)
        console.log(rolesList);
        setCheckBox(rolesList)
    }, [])

    // 全选
    const checkAll = () => {
        setCheckBox(getRolesLists.map((item) => item._id))
    }

    // 反选
    const invert = () => {
        setCheckBox(getRolesLists.map((item) => item._id).filter((value) => !checkBox.includes(value)))
    }

    // 处理单个复选框的选择
    const handleCheckboxChange = (roleId) => {
        if (checkBox.includes(roleId)) {
            setCheckBox(checkBox.filter(id => id !== roleId))
        } else {
            setCheckBox([...checkBox, roleId])
        }
    }

    const management = () => {
        updateUserRolesFromApi(route.id, { roles: checkBox })
        navigate('/acl/users')
    }

    return <div>
        <p>分配角色</p>
        <Button type='primary' onClick={checkAll}>全选</Button>
        <Button type='primary' onClick={invert}>反选</Button>
        {getRolesLists.map((item) => {
            return <div key={item._id}>
                <Checkbox 
                    checked={checkBox.includes(item._id)}
                    onChange={() => handleCheckboxChange(item._id)}
                >
                    {item.name}
                </Checkbox>
            </div>
        })}
        <Button type='primary' onClick={management}>角色管理</Button>
    </div>
}

export default Assign;